package com.qfedu.edu.seckill.orderservice.slot.impl;

import com.qfedu.edu.seckill.constance.RedisConstance;
import com.qfedu.edu.seckill.exception.BusinessException;
import com.qfedu.edu.seckill.manager.RedisManager;
import com.qfedu.edu.seckill.orderservice.slot.generic.GenericSlot;
import com.qfedu.edu.seckill.result.ResponseCode;
import com.qfedu.edu.seckill.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xiaobobo
 * @title: BlackSlot
 * @projectName cd-java-2404-seckill-parent
 * @description: TODO
 * @date 2025/2/6  9:40
 */
@Component
@Slf4j
public class BlackSlot extends GenericSlot {

    @Autowired
    private RedisManager redisManager;

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }

    @Override
    public void dealRequest(HttpServletRequest request, HttpServletResponse response) {
       //首先获取ip地址
        String ipAddress = IpUtils.getIpAddress(request);
        //然后构建key
        String key = RedisConstance.getReqBlackPrefix() + ipAddress;
        //判断这个key在Redis中是否存在
        if (redisManager.hasKey(key)) {
            log.info("当前ip{}位于黑名单中无法访问", ipAddress);
            //这里可以直接抛出异常
            throw new BusinessException(ResponseCode.BLACK_EXCEPTION);
        }
        log.info("黑名单校验通过....");
    }
}
